package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.swing.*;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TodayBestService {
    @Autowired
    private UserService userService;
    @Autowired
    private RecommendUserService recommendUserService;
    @Autowired
    private UserInfoService userInfoService;
    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;


    /**
     * 今日最佳佳人
     *
     * @param token
     * @return
     */
    public TodayBest queryTodayBest(String token) {


        //校验token是否有效，通过SSO的接口进行校验,获取到用户的id
        User user = this.userService.queryUserByToken(token);
        if (null == user) {
            //token非法或则已经过期
            return null;
        }


        //查询推荐用户（今日佳人）,根据用户id获取到佳人的id
        TodayBest todayBest = this.recommendUserService.queryTodayBest(user.getId());
        if (null == todayBest) {
            //给出默认的推荐给用户
            todayBest = new TodayBest();
            todayBest.setId(defaultUser);
            todayBest.setFateValue(81L);//固定值
        }
        //根据佳人的id,补全佳人信息
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(todayBest.getId());
        if (null == userInfo) {
            return null;
        }
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ","));
        todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "women");
        todayBest.setAge(userInfo.getAge());
        //返回最佳人
        return todayBest;
    }

    /**
     * 今日推荐
     *
     * @param token
     * @param queryParam
     * @return
     */
    public PageResult queryRecommendation(String token, RecommendUserQueryParam queryParam) {
        //验证token
        User user = userService.queryUserByToken(token);
        if (null == user) {
            //token已经过期或者非法
            return null;
        }
        //根据用户的id在mengob查询,所有的佳人
        PageResult pageResult = new PageResult();
        pageResult.setPage(queryParam.getPage());
        pageResult.setPagesize(queryParam.getPagesize());
        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendation(user.getId(), queryParam.getPage(), queryParam.getPagesize());
        List<RecommendUser> records = pageInfo.getRecords();
        //判断是否查询到推荐的用户列表
        if (CollectionUtils.isEmpty(records)) {
            return pageResult;
        }
        //填充个人信息
        //收集推荐的用户的id
        Set<Long> set = new HashSet<>();
        for (RecommendUser record : records) {
            set.add(record.getUserId());
        }
        //查询数据库里的对应的小姐姐的信息
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        //用户id参数
        queryWrapper.in("user_id", set);
        //需要的性别参数查询
        if (StringUtils.isNotEmpty(queryParam.getGender())) {
            queryWrapper.eq("sex", StringUtils.equals(queryParam.getGender(), "man") ? 1 : 2);
        }
        //需要对城市参数查询
        if (StringUtils.isNotEmpty(queryParam.getCity())) {
            queryWrapper.like("city", queryParam.getCity());
        }
        //设置年龄参数,条件,小于等于
        if (queryParam.getAge() != null) {
            queryWrapper.le("age", queryParam.getAge());
        }
        //调用userInfoService,通过远程的rpc调用,在数据库中查询
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        if (CollectionUtils.isEmpty(userInfoList)) {
            //没有用户
            return pageResult;
        }
        //复制
        List<TodayBest> todayBestlist = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
            todayBest.setAge(userInfo.getAge());
            //缘分值
            for (RecommendUser record : records) {
                if (record.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    double score = Math.floor(record.getScore());//取整
                    todayBest.setFateValue(Double.valueOf(score).longValue());
                    break;
                }
            }
            todayBestlist.add(todayBest);
        }
        //按照缘分值进行倒序排序
        Collections.sort(todayBestlist, new Comparator<TodayBest>() {
            @Override
            public int compare(TodayBest o1, TodayBest o2) {

                return new   Long (o2.getFateValue()-o1.getFateValue()).intValue();
            }
        });
        pageResult.setItems(todayBestlist);
        return pageResult;
    }
}
